package service.impl;


import dao.*;
import model.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import service.IGoodsService;
import util.DateUtil;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @aythor:侯仪澳
 * @data:2022/7/21
 */
@Service
public class GoodsService implements IGoodsService {
    @Autowired
    private IGoodsDao goodsDao;
    @Autowired
    private IUserDao userDao;
    @Autowired
    private IOrderDao orderDao;
    @Autowired
    private ITradeDao tradeDao;
    @Autowired
    private IOrderGoodsDao orderGoodsDao;
    @Autowired
    private IShopCarDao shopCarDao;

    //查询所有商品
    @Override
    public List<Goods> queryAllGoods(Goods goods) {
        return goodsDao.queryAllGoods(goods);
    }

    //查询所有商品分页
    @Override
    public Map<String,Object> queryGoodsByStatus(Goods goods,Integer pageNo) {
        //如果页码为空或者小于1   则显示第一页
        if (pageNo == null || pageNo < 1){
            pageNo = 1;
        }
        int rowCount = 8; //每一页行数
        int limitFirst = (pageNo-1)*rowCount;//计算数据库分页行号
        Map<String, Object> map = new HashMap<>();
        map.put("goods", goods);
        map.put("rowCount", rowCount);
        map.put("limitFirst", limitFirst);
        List<Goods> list = goodsDao.queryGoodsByStatus(map);
        //计算总页数
        List<Goods> list1 = goodsDao.queryAllGoods(goods);//获得所有的数据总数
        int totalPage = (int)(list1.size() / rowCount);
        if (list1.size() % rowCount != 0 ) {
            totalPage += 1;
        }
        if (totalPage == 0){
            totalPage = 1;
        }
        Map<String, Object> resMap = new HashMap<>();
        resMap.put("list", list);
        resMap.put("pageNo", pageNo);
        resMap.put("totalPage", totalPage);
        return resMap;
    }

    //添加商品
    @Override
    public String addOneGoods(Goods goods) {
        if ((goods.getgName() == null || goods.getgName().isEmpty())
                && (goods.getImgUrl() ==null || goods.getImgUrl().isEmpty())
                && goods.getgCount() == null
                && goods.getgPrice() == null
                && goods.getsId() == null){
            return "2";
        }
        int count = goodsDao.addOneGoods(goods);
        if (count == 1){
            return "1";
        }else {
            return "0";
        }
    }

    //修改上架下架状态值
    @Override
    public String updateGoodsBatch(List<Goods> list) {
        int count = goodsDao.updateGoodsBatch(list);
        if (count == 1){
            return "1";
        }else {
            return "0";
        }
    }

    //一级分类
    @Override
    public List<Goods> queryFirstSort(Goods goods) {
        return goodsDao.queryFirstSort(goods);
    }

    //二级分类
    @Override
    public List<Goods> querySecondSort(Goods goods) {
        return goodsDao.querySecondSort(goods);
    }

    //修改货物信息
    @Override
    public String updateOneGoods(Goods goods) {
        int count = goodsDao.updateOneGoods(goods);
        if (count == 1){
            return "1";
        }else {
            return "0";
        }
    }

    //创建订单，支付之前
    @Override
    @Transactional
    public Map<String, Object> createOrder(Integer carId,Integer gId, Integer buyCount, Integer uId) {

        // 1 扣减库存
        Map<String,Integer> map = new HashMap<>();
        Map<String,Object> returnMap = new HashMap<>();
        map.put("gId",gId);
        map.put("buyCount",buyCount);
        int res = goodsDao.subCount(map);
        if (res < 1) {
            // 扣减库存失败
            returnMap.put("code",0);
            returnMap.put("msg","库存不足，订单创建失败");
            return returnMap;
        }

        // 2 生成订单
        // 2-1 生成订单号
        List<User> list = userDao.queryAllUser(new User(uId));
        String phone = list.get(0).getuPhone();
        // 获得手机号后四位，生成订单号后缀
        String suffix = phone.substring(phone.length()-4);
        // 生成订单号前缀
        String prefix = DateUtil.dateFormat();
        String orderNo = prefix + suffix;
        // 2-2 插入订单记录

        Order order = new Order();
        order.setOrderNo(orderNo);
        order.setuId(uId);
        // 查询商品信息
        Goods goods =  goodsDao.queryAllGoods(new Goods(gId)).get(0);
        // 订单支付金额
        BigDecimal orderMoney = goods.getgPrice().multiply(new BigDecimal(buyCount));
        order.setOrderMoney(orderMoney);
        //创建订单
        orderDao.addOneOrder(order);

        //5)插入订单商品记录order_goods
        OrderGoods orderGoods = new OrderGoods();
        orderGoods.setOrderNo(orderNo);
        orderGoods.setgId(gId);
        orderGoods.setgName(goods.getgName());
        orderGoods.setgPrice(goods.getgPrice());
        orderGoods.setBuyCount(buyCount);
        orderGoods.setTotalMoney(orderMoney);
        orderGoodsDao.addOneOrderGoods(orderGoods);

        //从购物车里购买，删除购物车里的商品
        if (carId != null){
            shopCarDao.deleteShopCar(carId);
        }

        //返回值
        returnMap.put("code",1);
        returnMap.put("msg","订单创建成功");
        returnMap.put("goods",goods);
        returnMap.put("order",order);
        return returnMap;
    }

    //生成交易流水
    @Override
    @Transactional
    public Map<String,Object> pay(Integer uId, String pass, String orderNo) {
        Map<String,Object> map = new HashMap<>();
        //1、验证密码
        List<User> list = userDao.queryAllUser(new User(uId, pass));
        if (list.size() < 1) {
            // 扣减库存失败
            map.put("code", 0);
            map.put("msg","密码错误");
            return map;
        }
        //2、扣款
        Order order = orderDao.queryAllOrder(new Order(orderNo)).get(0);
        /**
         * int result = bigdemical1.compareTo(bigdemical2)
         * result = -1,表示bigdemical1小于bigdemical2；
         * result = 0,表示bigdemical1等于bigdemical2；
         * result = 1,表示bigdemical1大于bigdemical2；
         */
        if (list.get(0).getuMoney().subtract(order.getOrderMoney()).compareTo(new BigDecimal(0))==-1){
            // 余额不足
            map.put("code", 0);
            map.put("msg","余额不足");
            return map;
        }
        User upUser = new User();
        upUser.setId(uId);
        upUser.setuMoney(list.get(0).getuMoney().subtract(order.getOrderMoney()));
        //更新用户账户余额
        userDao.updateUserMoney(upUser);
        //3、修改订单状态
        Order upOrder = new Order();
        upOrder.setOrderStatus(2);
        upOrder.setOrderNo(orderNo);
        orderDao.updateOrderStatus(upOrder);

        //4、生成交易流水
        Trade trade = new Trade();
        trade.setuId(uId);
        trade.setOrderNo(orderNo);
        trade.setTradeMoney(order.getOrderMoney());
        trade.setTradeType(2);
        //插入交易流水记录
        tradeDao.addOneTrade(trade);
        map.put("code", 1);
        map.put("msg", "支付成功");
        return map;
    }


}
